package study.javaee.practice.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.OncePerRequestFilter;
import study.javaee.practice.common.exception.ApiException;
import study.javaee.practice.property.SecurityProperty;
import study.javaee.practice.service.AsymEncService;
import study.javaee.practice.service.SymEncService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 处理客户端提交的加密数据
 */
@Component
@WebFilter("/")
@Order(1)
public class DataDecryptFilter extends OncePerRequestFilter {

    @Autowired
    DataDecryptFilter(AsymEncService asymEncService, SymEncService symEncService, SecurityProperty securityProperty){
        MyRequestParamsWrapper.init(asymEncService, symEncService, securityProperty);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 对所有post 和 put方法过滤
        String method = request.getMethod();
        if(method.equals(RequestMethod.POST.toString()) || method.equals(RequestMethod.PUT.toString())){
            try{
                ServletRequestWrapper requestWrapper = new MyRequestParamsWrapper(request);
                filterChain.doFilter(requestWrapper, response);
            }catch (ApiException e){ // 出现异常
                request.setAttribute("code", e.getApiErrorCode().getCode());
                request.setAttribute("message", e.getApiErrorCode().getMessage());
                request.getRequestDispatcher("/rest_err").forward(request, response);
            }

        }else {
            filterChain.doFilter(request, response);
        }
    }
}
